#include "ijkmp.h"
#include "QtDebug"
#include "ffplayer.h"
#include "msg.h"

ijkmp::ijkmp()
{

}

int ijkmp::ijkmp_create(std::function<int (void *)> msg_loop)
{
    int ret =0;
    ffplayer_ = new FFPlayer();
    if(!ffplayer_) {
        qDebug("new FFPlayer failed");
        return -1;
    }

    msg_loop_ = msg_loop ;

    ret = ffplayer_->ffp_create();
    if(ret<0){
        qDebug("new FFPlayer failed");
        return ret;
    }
    return ret;
}

int ijkmp::ijkmp_set_data_source(const char *url)
{
    if(!url) {
        return -1;
    }
    data_source_  = strdup(url);
    return 0;
}

int ijkmp::ijkmp_prepare_async()
{

    mp_state_ = MP_STATE_ASYNC_REPARING;
    //启动消息队列
    msg_queue_start(&ffplayer_->msg_queue_);
    //msg_queue_start(ffplayer_->msg_queue);
    //创建循环线程
    msg_thread_ = new std::thread(&ijkmp::ijkmp_msg_loop,this,this);
    //调用ffplayer
    int ret = ffplayer_->ffp_prepare_async_l(data_source_);
    if(ret<0){
        qDebug("ffp_prepare_async_l failed");
        return -1;
    }
    return ret;
}

int ijkmp::ijkmp_start()
{
    ffp_notify_msg1(ffplayer_,FFP_MSG_START);
    std::cout<<__FUNCTION__<<" running" <<std::endl;

    return 0;
}

int ijkmp::ijkmp_stop()
{

}

void ijkmp::ijk_log(int a)
{
    std::cout<<"ijk get and log:";
    if(a==FFP_MSG_FIND_STREAM_INFO){
        std::cout<<"FFP_MSG_FIND_STREAM_INFO";
    }else{
        if(a==FFP_MSG_OPEN_INPUT){
            std::cout<<"FFP_MSG_OPEN_INPUT";
        }
    }
    std::cout<<std::endl;
}

int ijkmp::ijkmp_get_msg(AVMessage *msg, int block)
{
    for(;;){
        int continue_wait_next_msg =0;
        int ret=0;
        ret = msg_queue_get(&(this->ffplayer_->msg_queue_),msg,block);
        if(ret < 0){
            break;
        }
        switch (msg->what) {
        case MSG_FULSH:
            //continue_wait_next_msg=1;
            break;
        case FFP_MSG_PREPARED:
            //continue_wait_next_msg =1 ;
        break;
        case FFP_MSG_OPEN_INPUT:
            ijk_log(FFP_MSG_OPEN_INPUT);
        break;
        case FFP_MSG_FIND_STREAM_INFO:
            ijk_log(FFP_MSG_FIND_STREAM_INFO);
        break;
        default:
        std::cout << __FUNCTION__<< " default:" << msg->what<<std::endl;

            break;
        }
        if (continue_wait_next_msg) {
            msg_free_res(msg);
            continue;
        }
        return ret;
    }
    return -1;
}



void ijkmp::ijk_addvideoRefleshcallback(std::function <int (const Frame *)> callback)
{
    ffplayer_->add_refresh_callback(callback);
}


